package oa.base.util.xml;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * xml 文件解析
 * 
 * @author lilang
 * 
 */
public class XmlUtil {

	/**
	 * 创建文档
	 */
	public Document createXmlDocument() {
		return DocumentHelper.createDocument();
	}

	/**
	 * load 载入一个xml文档
	 * 
	 * @return 成功返回Document对象，失败返回null
	 * @param uri
	 *            文件路径
	 */
	public static Document load(String filename) {
		Document document = null;
		try {
			SAXReader saxReader = new SAXReader();
			document = saxReader.read(new File(filename));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return document;
	}

	/**
	 * string2Document 将字符串转为Document
	 * 
	 * @return
	 * @param s
	 *            xml格式的字符串
	 */
	public static Document string2Document(String s) {
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(s);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return doc;
	}
	/**
	 * 取得root 节点
	 * @param doc
	 * @return
	 */
	public static Element getRoot(Document doc){
		return doc.getRootElement();
	}
	
	
	/**
	 * 取得root 节点
	 * @param doc
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Element getNode(Element root,String id){
		List<Element> nodes = root.elements();
		for(Element element:nodes){
			if(id.equals(element.attribute("id").getText())){
				return element;
			}
		}
		return null;
	}
	
	/**
	 *  取得这个节点的 attr 值
	 * @param ment
	 * @param attr
	 * @return
	 */
	public static String getElementAttr(Element ment,String attr){
		return ment.attribute(attr).getText();
	}
	
	
	public static void main(String[] args) {
		Document doc = XmlUtil.load("D:/work_svn/google/cqoa/oa-base/src/main/resources/work-document.xml");
		Element root = doc.getRootElement();
		Element frist = XmlUtil.getNode(root, "ng");
		System.out.println(frist.asXML());
	}
	
}
